//
//  WBMainViewController.swift
//  ZWWEIBO
//
//  Created by xzw on 2017/11/21.
//  Copyright © 2017年 xzw. All rights reserved.
//

import UIKit
import SVProgressHUD

class WBMainViewController: UITabBarController {

    private var timer : Timer?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //初始化
        setupChildControllers()
        setupComposeButton()
        setupTimer()
        
        setupNewFeature() //设置新特性视图
        
        delegate = self //设置代理
        
        //登陆通知
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin), name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
        
    }
    
    deinit {
        //定时器销毁
        timer?.invalidate()
        NotificationCenter.default.removeObserver(self)
    }
    
    //portrait : 竖屏
    //landscape : 横屏
    //设置支持的方向之后，当前的控制器及子控制器都会遵守这个方向
    //如果播放视频，通常是通过modal展现的
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
        return .portrait
    }
    
     //MARK: - 登录通知方法
    @objc private func userLogin(n:Notification){

        var dismissTime = DispatchTime.now()
        if n.object != nil { //token过期
            
            SVProgressHUD.setDefaultMaskType(.gradient)
            SVProgressHUD.showInfo(withStatus: "用户登录已超时，请重新登录")
            dismissTime = DispatchTime.now() + 2
            print("用户登录已超时，请重新登录")
        }
        
        DispatchQueue.main.asyncAfter(deadline: dismissTime) {
            SVProgressHUD.setDefaultMaskType(.clear)
            let nav = UINavigationController(rootViewController: WBOAuthViewController())
            self.present(nav, animated:true, completion: nil)
        }
        
    }
    
     //MARK: - 监听方法
    @objc private func composeStatus() {
        print("撰写微博")
        let vc = UIViewController()
        vc.view.backgroundColor = UIColor.red
        let nav = UINavigationController(rootViewController: vc)
        present(nav, animated: true, completion: nil)
    }
    
     //MARK: - 私有控件
    private lazy var composeButton:UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName:"tabbar_compose_button")
}

 //MARK: -UITabBarControllerDelegate
extension WBMainViewController:UITabBarControllerDelegate{
    
    /// 点击tabarItem将要切换
    ///
    /// - Parameters:
    ///   - tabBarController: tabBarController
    ///   - viewController: 目的控制器
    /// - Returns: 是否切换到目的控制器
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        
        //1.获取目标控制器index
        let toIdx = (childViewControllers as NSArray).index(of:viewController)
        
        //判断当前控制器是首页，且点击首页tabbarItem
        if selectedIndex == 0 && toIdx == selectedIndex {
            
            //1.首页tableview滚动到顶部
            let nav = childViewControllers[0] as! UINavigationController
            let vc =  nav.viewControllers[0] as! WBHomeViewController
            vc.tableView?.setContentOffset(CGPoint(x: 0, y: -64)
                , animated: true)
            
            //2.刷新表格数据,延时用于解决talbeview不能滚动到顶部
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: {
                vc.loadData()
            })
            
            //清楚tableItem的badgeValue
            vc.tabBarItem.badgeValue = nil
            UIApplication.shared.applicationIconBadgeNumber = 0
            
        }
        
        return !viewController.isMember(of: UIViewController.self)
    }
}

 //MARK: - 定时器相关
extension WBMainViewController {
    
    private func setupTimer(){
        timer = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
    }
    
    @objc private func updateTimer(){
        
        if !WBNetworkManager.sharedInstance.userLogin {//未登录，不用网络请求
            return
        }
        
        //获取未读
        WBNetworkManager.sharedInstance.getUnread { (count) in
            
            print("获取未读 \(count) 条")
            //设置首页tabBarItem的badgeValue
            self.tabBar.items?[0].badgeValue = count > 0 ? "\(count)" : nil
            
            //设置app应用图标的提醒数字，iOS8以后需要用户授权
            UIApplication.shared.applicationIconBadgeNumber = count
        }
    }
}

 //MARK: - 新特性视图
extension WBMainViewController{
    
    private func setupNewFeature(){
        
        //0.判断是否登录
        if !WBNetworkManager.sharedInstance.userLogin{
            return
        }
        
        //1.检查版本是否更新
        let v = isNewversion ? WBNewFeatureView.loadNewFeatureView() : WBWelcomView.loadWelcomeView()
        
        //3.添加视图
        view.addSubview(v)
    }
    
    //判断版本是否更新
    //appstore每次升级应用程序，版本号都需要更新
    //组成 主版本号，次版本号，修订版本号
    //主版本号：意味大的修改，使用者需要做大的适应
    //次版本号：意味着小的修改，某些函数和方法的使用或者参数有变化
    //修订版本号：修改bug,不会对使用者产生影响
    var isNewversion : Bool {
        
        //1.取当前的版本号
        //print(Bundle.main.infoDictionary)
        let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
        
        //2.取保存在document 目录中的之前版本号
        let path : String = ("version" as NSString).cz_appendDocumentDir()
        let sandboxVersion = try? String(contentsOfFile: path)
        
        //3.将当前版本号保存到沙盒
       try? currentVersion.write(toFile: path, atomically: true, encoding: .utf8)
        
        print(path)
        
        //4.返回两个版本号是否一致
        return currentVersion != sandboxVersion
        
    }
    
}


    //MARK: - 设置界面
extension WBMainViewController {
    
    //设置撰写按钮
    private func setupComposeButton(){
        tabBar.addSubview(composeButton)
        
        //计算按钮的宽高
        let count = CGFloat(childViewControllers.count)
        //tabarItem宽度
        let width = tabBar.bounds.width/count
        
        composeButton.frame = tabBar.bounds.insetBy(dx: 2*width, dy: 0)
        
        //按钮监听方法
        composeButton.addTarget(self, action: #selector(composeStatus), for: .touchUpInside)
    }
    
    
    //设置所有子控制器
    private func setupChildControllers(){
        
        //1.判断本地沙盒有没有main.json文件
        let documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (documentPath as NSString).appendingPathComponent("main.json")
        
        var data = NSData(contentsOfFile: jsonPath)
        if data == nil {
            //说明沙盒没有文件，加载本地bundle资源
            let path = Bundle.main.path(forResource: "main.json", ofType: nil)
            data = NSData(contentsOfFile:path!)
        }
        
        //沙盒有文件，data反序列化成数组
        guard  let array = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String : Any]] else{
            
            return
        }
    
        

        //遍历数组，创建子控制器
        var arraM = [UIViewController]()
        for dict in array! {
            arraM.append(controller(dict: dict))
        }
        
        //赋值
        viewControllers = arraM
    }
   
    /// 使用字典创建一个子控制器
    ///
    /// - Parameter dict: 信息字典[clsName,title,imageName]
    /// - Returns: 子控制器
    private func controller(dict:[String:Any]) -> UIViewController{
        
        guard let clsName = dict["clsName"] as? String,
              let title = dict["title"] as? String,
              let imageName = dict["imageName"] as? String,
              let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? WBBaseViewController.Type,
              let vistorInfo = dict["visitorInfo"] as? [String : String] else {
                
              return UIViewController()
        }
        
        
        //创建视图控制器
        let vc = cls.init()
        vc.title = title
        
        //设置访客视图信息
        vc.vistorInfoDic = vistorInfo
        
        vc.tabBarItem.image = UIImage(named: "tabbar_"+imageName)
        vc.tabBarItem.selectedImage = UIImage(named:"tabbar_"+imageName+"_selected")?.withRenderingMode(.alwaysOriginal)
        vc.tabBarItem.setTitleTextAttributes([NSAttributedStringKey.foregroundColor:UIColor.orange],
                                         for: .highlighted)
        vc.tabBarItem.setTitleTextAttributes([NSAttributedStringKey.font:UIFont.systemFont(ofSize: 12)], for: .normal)
        
        
        let nav = WBNavigationController(rootViewController: vc)
        return nav
    }
}
